package com.yearner.reviewplan.manage.system;

import com.google.gson.Gson;
import com.yearner.reviewplan.common.aspect.AuthTokenV1;
import com.yearner.reviewplan.common.aspect.WebLog;
import com.yearner.reviewplan.common.enums.Consts;
import com.yearner.reviewplan.common.model.Result;
import com.yearner.reviewplan.manage.system.bean.MenuVo;
import com.yearner.reviewplan.manage.system.bean.RouterVo;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author pengyg
 * @since 2020/1/16
 */
@Api
@CrossOrigin
@RestController
@RequestMapping("api/system")
public class SystemController {
    @Autowired
    UserPermController permController;
    @Autowired
    UserRouterController routerController;

    private static final String NOW_ADMIN_ID = "U1";
    private Gson gson = new Gson();
    /**
     * 菜单与路由
     */
    @AuthTokenV1
    @GetMapping("/menus")
    public Result<Object> menus(HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>(2);
        List<MenuVo> menuVoList = permController.getMenuVoList();
        List<RouterVo> routerVoList = routerController.getRouterVoList();
        validByRole(request, menuVoList, routerVoList,map);
//        map.put("accessMenus", menuVoList);
//        map.put("accessRoutes", routerVoList);
        // todo isAdmin
        map.put("isAdmin", true);
        // 先使用默认的忽略null值，再将其转为map （child为null时页面加载失败）
        return Result.success(gson.fromJson(gson.toJson(map), HashMap.class));

    }

    private void validByRole(HttpServletRequest request, List<MenuVo> menuVos, List<RouterVo> routerVos,HashMap<String, Object> map) {

        // todo 在权限管理完善之前，先根据管理员id来判断
        Integer key = 1;
        if (!NOW_ADMIN_ID.equals(request.getAttribute(Consts.CURRENT_USER_ID))) {
            // 新建一个副本，因为原有的 List 在controller被持有了
            menuVos = new ArrayList<>(menuVos);
            routerVos = new ArrayList<>(routerVos);
            // 如果不是admin，就剪辑掉系统管理菜单和路由
            menuVos.removeIf(menuVo -> key.equals(menuVo.getMenuId()));
            routerVos.removeIf(routerVo ->  key.equals(routerVo.getRouterId()));
        }
        map.put("accessMenus", menuVos);
        map.put("accessRoutes", routerVos);
    }

    @WebLog
    @GetMapping("/myUrl")
    public Result<String> myUrl(HttpServletRequest request) {
        StringBuffer requestUrl = request.getRequestURL();
        int lastIndex = requestUrl.lastIndexOf("system");
        return Result.success("",requestUrl.substring(0, lastIndex));
    }
}
